<template>
  <div class="form-container">
    <el-card class="box-card">
      <div class="card-header">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/teachers/teachers'}">专家师资</el-breadcrumb-item>
          <el-breadcrumb-item>师资添加/编辑</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form :model="form"  ref="baseForm" label-width="120px">
        <div class="head-card">
          <!-- 讲师名称 -->
          <el-form-item label="讲师名称：" prop="user_name" class="required-item">
            <el-input
              v-model="form.teaName"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 职称 -->
          <el-form-item label="职称：" prop="user_dev">
            <el-input
              v-model="form.teaZc"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 专业领域 -->
          <el-form-item label="专业领域：" prop="user_phoneno">
            <el-input
              v-model="form.teaReg"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 所在地区  -->
          <el-form-item label="所在地区：" prop="user_dev" >
            <el-input
              v-model="form.teaDq"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 联系方式  -->
          <el-form-item label="联系方式：" prop="user_dev" >
            <el-input
              v-model="form.teaphone"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 执照起始日期 -->
          <el-form-item label="参加工作时间：">
            <el-date-picker
              v-model="form.teaWorkTime"
              type="date"
              placeholder="选择日期"
              style="width: 637px;">
            </el-date-picker>
          </el-form-item>

          <!-- 头像 -->
          <el-form-item label="头像：">
<!--            <div class="demo-image__preview">-->
<!--              <el-image-->
<!--                style="width: 200px; height: 200px"-->
<!--                :src="form.teaTouX"-->
<!--                :preview-src-list="srcList">-->
<!--              </el-image>-->
<!--            </div>-->
<!--            <div class="upload-tip">建议尺寸：300×300px，支持JPG/PNG格式</div>-->
            <!--    头像-->
            <div>
              <el-upload
                class="avatar-uploader"
                action="#"
                :auto-upload="false"
                :on-change="changeavart"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.teaTouX" :src="form.teaTouX" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="upload-tip">展示于列表和详情页。图片小于1M。
              建议上传 3:4 比例（如750x1000px）的JPG/PNG/WebP格式。</div>
          </el-form-item>

          <!-- 视频 -->
          <el-form-item label="视频：">
<!--            <div class="demo-image__preview">-->
<!--              <el-image-->
<!--                style="width: 200px; height: 200px"-->
<!--                :src="form.teaVieo"-->
<!--                :preview-src-list="srcList">-->
<!--              </el-image>-->
<!--            </div>-->
<!--            <div class="upload-tip">建议尺寸：300×300px，支持JPG/PNG格式</div>-->
            <el-upload
              class="upload-demo"
              ref="upload"
              action="#"
              :on-change="handleFileChange"
              :show-file-list="true"
              :file-list = "form.teaVieo"
              :auto-upload = "false"
              :limit ="1"
            >
              <el-button size="small" type="primary">上传课件视频</el-button>
            </el-upload>
          </el-form-item>

          <!-- 讲师介绍 -->
          <el-form-item label="讲师介绍：" prop="user_phoneno" >
            <el-input
              v-model="form.teaDetails"
              placeholder="请输入"
              clearable
              type="textarea"
              rows="10"
            ></el-input>
          </el-form-item>
        </div>
        <!--         表单操作 -->
        <el-form-item>
          <el-button type="primary" :disabled="isButtonDisabled" @click="saveTeachers">保存</el-button>
          <el-button type="primary" @click="teacherCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {createbt, fileuploadres, regjguserfail, updatebt, uploadres} from "../../api/InstitutionApi";

export default {
  data() {
    return {
      form: {
        teaName:'',
        teaZc:'',
        teaReg: '',
        teaDq:'',
        teaphone:'',
        teaWorkTime: '',
        teaTouX:'',
        teaTouXCode:'',
        teaVieo: [],
        teaVieoCode:'',
        teaDetails: ''
      },
      base64Data:'',
      type: [
        {
          value: '护理',
          label: '护理'
        }, {
          value: '康养',
          label: '康养'
        },
      ],
      // 图片存储
      logoimgurl:'',
      doorimgurl:'',
      inImgurl: [],
      zizhaoImg: '',
      srcList:[],
      // 弹窗存储
      editFormVisible: false,
      unReview:'',
      addressOptions: [
        {
          value: 'zhejiang',
          label: '浙江省',
          children: [
            {
              value: 'hangzhou',
              label: '杭州市',
              children: [
                { value: 'xihu', label: '西湖区' },
                { value: 'binjiang', label: '滨江区' }
              ]
            }
          ]
        },
        {
          value: 'jiangsu',
          label: '江苏省',
          children: [
            {
              value: 'nanjing',
              label: '南京市',
              children: [
                { value: 'xuanwu', label: '玄武区' },
                { value: 'qinhuai', label: '秦淮区' }
              ]
            }
          ]
        }
      ],
      getTeaData:{},  ////接收数据
      isEdit: false ///是否编辑
    }
  },
  created() {
    // 对于 path: '/detail/:flowId' 的匹配
    this.getTeaData = this.$route.query.teacherCode;
    if(!this.getTeaData || Object.keys(this.getTeaData).length === 0) {
        this.isEdit = false
    } else {
      this.isEdit = true
      this.getTeacherDate()
    }
    console.log('讲师：',this.getTeaData,this.isEdit);

  },
  computed: {
    isButtonDisabled() {
      // return this.form.base.cur_status === 2; // 可以扩展其他条件，如 || this.isLoading
    }
  },
  methods: {
    disabled() {
      return disabled
    },
    // 接收传递数据
    getTeacherDate() {
      this.form = {
        teaName : this.getTeaData.bt_name,
        teaZc : this.getTeaData.bt_zhicheng,
        teaReg : this.getTeaData.bt_zyly,
        teaDq : this.getTeaData.bt_addr,
        teaWorkTime : this.getTeaData.bt_workdate,
        teaTouX : this.getTeaData.bt_header_uri[0].url,
        teaTouXCode : this.getTeaData.bt_header_uri[0].imguri,
        teaVieo : this.chanageVideoArray(this.getTeaData.bt_person_video_uri[0]),
        teaVieoCode : this.getTeaData.bt_person_video_uri[0].imguri,
        teaDetails : this.getTeaData.bt_desc,
        teaphone : this.getTeaData.bt_phoneno
      }
      console.log('讲师：',this.form);
    },

    // 处理视频格式
    chanageVideoArray(urlArray) {
      return [{
        name: urlArray.imgname,
        url: urlArray.url
      }]

    },

    // 保存、更新讲师信息
    saveTeachers() {
      if(!this.isEdit) {
        // 新增
        createbt({
          "btname": this.form.teaName, //#师资名称
          "btphoneno": this.form.teaphone, //#师资手机号
          "btzhicheng": this.form.teaZc, //#师资职位
          "btzyly": this.form.teaReg, //#师资专业领域
          "btaddr": this.form.teaDq, //#师资地址
          "btworkdate": this.form.teaWorkTime, //#师资工作日期
          "btheaderuri": this.form.teaTouXCode, //#师资头像uri
          "btpersonvideouri": this.form.teaVieoCode,  //#师资个人视频uri
          "btdesc": this.form.teaDetails,  //#师资描述
        }).then(res=> {
          console.log('讲师保存',res)
          this.$router.push({
            path: '/teachers/teachers',
            query: ''
          });
        })
      } else {
      //  编辑
        updatebt({
          "btcode": this.getTeaData.bt_code, ///师资code
          "btname": this.form.teaName, //#师资名称
          "btphoneno": this.form.teaphone, //#师资手机号
          "btzhicheng": this.form.teaZc, //#师资职位
          "btzyly": this.form.teaReg, //#师资专业领域
          "btaddr": this.form.teaDq, //#师资地址
          "btworkdate": this.form.teaWorkTime, //#师资工作日期
          "btheaderuri": this.form.teaTouXCode, //#师资头像uri
          "btpersonvideouri": this.form.teaVieoCode,  //#师资个人视频uri
          "btdesc": this.form.teaDetails,  //#师资描述
        }).then(res=> {
          console.log('讲师编辑',res)
          this.$router.push({
            path: '/teachers/teachers',
            query: ''
          });
        })
      }

    },
    // 取消
    teacherCancel() {
      // 跳转页面的三种方式
      // 方式1：通过 path 跳转
      // this.$router.push({
      //   path: `/enterprises/EnEdit/:index`
      // });
      // 方式2：通过 name 跳转（推荐）
      // this.$router.push({
      //   name: 'enedit',
      //   params: { index: index }
      // });

      // 方式3：带查询参数（显示在URL中）
      this.$router.push({
        path: '/teachers/teachers',
        query: ''
      });

    },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },


    // 审核不通过
    reviewUnBy(flowid){
      console.log('驳回-1：',flowid);
      regjguserfail({
        "flowid": flowid,
        "flowmsg": this.unReview,
      }).then(res => {
        console.log('驳回：',res,this.unReview);
        this.editFormVisible = false
      })
    },
    resetForm() {
      this.$refs.baseForm.resetFields();
      this.form.businessStatus = '营业中';
      this.form.logoUrl = '';
    },
    //头像
    // 头像上传
    // 自定义上传方法
    customUpload(params) {
      uploadres({
        "usercode": localStorage.getItem('usercode'), //#用户标识号
        "rescode": this.base64Data,//#图片资源的base64码
        "restype":"0",//#资源类型，0企业营业执照，1企业logo，2门头照，3企业环境,4个人简介视频
        "resdesc":"图片"  //图片描述"
      }).then(res => {
        console.log('图片上传：',res)
        this.form.teaTouXCode = res.data.base_info
      })

    },

    // 上传前将图片转为base64
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 方法1：直接使用完整的DataURL（推荐）
          this.form.teaTouX = reader.result; // 带前缀的完整Base64，可直接用于<img>显示

          // 方法2：如果需要纯Base64（去掉前缀）
          const pureBase64 = reader.result.split(',')[1];
          this.base64Data = pureBase64;

          // console.log('完整DataURL:', reader.result);
          // console.log('纯Base64:', pureBase64);

          resolve(true); // 必须返回true才会继续上传
          this.customUpload()
        };
        reader.onerror = error => {
          console.error('文件读取失败:', error);
          reject(error);
        };
      });
    },
    changeavart(file){
      console.log('头像：',file);
      this.beforeUpload(file.raw)
    },
    handleAvatarSuccess(res, file) {
      this.form.teaTouX = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log('上传格式：',file);
      const isJPG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    //头像结束

  // 视频上传开始
  // 当文件变化时
  async handleFileChange(file, fileList) {
    // 1.当文件变化时，需要首先将临时文件与文件名称存储入相应的数组对象中
    // 获取文件的临时路径（不同浏览器兼容处理）
    const tempPath = file.url || URL.createObjectURL(file.raw);
    // 调用存储函数
    const newVideo = {
      name: file.name,
      url: tempPath
    };
    let formData = new FormData();
    // const fileupdown = this.fileList[0].raw; // 获取原始文件对象
    const fileupdown = file.raw
    // 文件形式上传
    formData.append('restype', '10'); // 资源类型：10=视频
    formData.append('resfile', fileupdown);
    console.log('当前文件列表:', formData);
    // 以文件形式上传视频到服务端
    this.fileuploadres(formData,newVideo)
  },

  // 以文件形式上传视频
  fileuploadres(formData,newVideo) {
    // 显示加载中
    const loading = this.$loading({
      lock: true,
      text: '视频上传中', // 初始文本
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    fileuploadres(formData,{
      headers:{
        'Content-Type': 'multipart/form-data' // 必须设置
      },
      onUploadProgress: (progressEvent) => {
        // 上传进度显示
        const percent = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        // loading.setText(`视频上传中 ${percent}%`);
        loading.setText(`视频上传中`);
      }
    }).then(res => {
      // 上传成功
      loading.close();
      this.$message.success('视频上传成功');
      console.log('video:',res )
      let resCode = res.data.res_code;
      this.$set(this.form,'teaVieo',[{name: newVideo.name, url: newVideo.url}])
      this.$set(this.form,'teaVieoCode',resCode)
      console.log('视频上传后:',this.form);
    })
  },
  //   视频上传结束

  }
}
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 20px auto;
}

.head-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 30px;
}

.card-select {
  padding-left: 40px;
  font-size: 14px;
  margin-bottom: 30px;

}

.form-title {
  font-size: 18px;
  font-weight: bold;
}

.required-item >>> .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>
